package com.creat;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import com.util.*;
import org.junit.Test;

import com.db.ColumnClass;

import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.NullCacheStorage;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class creat {

    //进行测试
    @Test
    public  void test() throws Exception{
    	creat codeGenerateUtils = new creat();
        ProjectUtil projectUtil = new ProjectUtil();
        projectUtil.setDISKPATH(Constant.DISKPATH);
        projectUtil.setProjectname("devops-devops");


        //生成文件目录
        List<String> list = new ArrayList();
        list.add(Constant.DISKPATH+projectUtil.getProjectname()+"/src/main/java/com/devops/devops/controller");
        list.add(Constant.DISKPATH+projectUtil.getProjectname()+"/src/main/java/com/devops/devops/domain");
        list.add(Constant.DISKPATH+projectUtil.getProjectname()+"/src/main/java/com/devops/devops/mapper");
        list.add(Constant.DISKPATH+projectUtil.getProjectname()+"/src/main/java/com/devops/devops/service/impl");
        list.add(Constant.DISKPATH+projectUtil.getProjectname()+"/src/main/java/resources/mapper/devops");
        projectUtil.setFileDirectory(list);













        //生成和数据库表相关文件 doamain controller mapper serviceimpl service xml
        List<TableUtil>  tableUtils = new ArrayList<>();
        TableUtil tableUtil = new TableUtil();
        tableUtil.setTablename("t_accusation_being_reported");
        tableUtil.setModelname("FC/MBBean.ftl");
        tableUtil.setSuffixname(FormatUtil.replaceUnderLineAndUpperCase(tableUtil.getTablename())+".java");
        tableUtil.setFillpath(Constant.DISKPATH+projectUtil.getProjectname()+"/src/main/java/com/devops/devops/domain/");
        tableUtil.setTableAnnotation("数据库命名规则");
        tableUtils.add(tableUtil);
        projectUtil.setTables(tableUtils);
















        //基础数据
        ConstantUtil constantUtil = new ConstantUtil();
        //模板文件
        Configuration CONFIGURATION = new Configuration(Configuration.VERSION_2_3_22);
        CONFIGURATION.setTemplateLoader(new ClassTemplateLoader(creat.class, "/com/model"));
        CONFIGURATION.setDefaultEncoding("UTF-8");
        CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        CONFIGURATION.setCacheStorage(NullCacheStorage.INSTANCE);

        codeGenerateUtils.generate(projectUtil,CONFIGURATION,constantUtil);
    }

    public  void generate(ProjectUtil projectUtil,Configuration CONFIGURATION,ConstantUtil constantUtil) throws Exception{
        //生成项目目录
        this.CreatFileDirectory(projectUtil);
        //生成表相关项目文件
        this.firstCreatFile(projectUtil,CONFIGURATION,constantUtil);
        //生成其他文件
    }



    //统一进行文件生成
    private void CreatFileDirectory(ProjectUtil projectUtil) throws Exception{
        System.out.println("一.项目目录准备生成");
        for (String FileDirectory:projectUtil.getFileDirectory()){
            System.out.println("项目目录生成: "+FileDirectory);
            FileUtil.CreatFile(FileDirectory);
        }
        System.out.println("项目目录已经生成");

    }
    //统一进行文件生成
    private void firstCreatFile(ProjectUtil projectUtil,Configuration CONFIGURATION,ConstantUtil constantUtil) throws Exception{
        System.out.println("二.项目文件准备生成");
        try {
            Connection connection = getConnection(constantUtil);
            DatabaseMetaData databaseMetaData = connection.getMetaData();
                for(TableUtil tableUtil:projectUtil.getTables()) {
                    ResultSet resultSet = databaseMetaData.getColumns(null, "%", tableUtil.getTablename(), "%");
                    //生成不需要数据库字段
                    Map<String, Object> dataMap1 = assembleMap(resultSet, "1",constantUtil,tableUtil);
                    //需要数据库字段
                    Map<String, Object> dataMap = assembleMap(resultSet, "2",constantUtil,tableUtil);
                    String url = tableUtil.getFillpath() +  tableUtil.getSuffixname();
                    File mapperFile = new File(url);
                    generateFileByTemplate(tableUtil.getModelname(), mapperFile, dataMap,CONFIGURATION);
                    System.out.println("项目文件生成: "+url);
                }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


   //根据模板生成文件
    private void generateFileByTemplate(final String templateName,File file,Map<String,Object> dataMap,Configuration CONFIGURATION) throws Exception{
        Template template = getTemplate(templateName,CONFIGURATION);
        FileOutputStream fos = new FileOutputStream(file);
        Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"),10240);
        template.process(dataMap,out);
    }
    
    //组装map数据
    private Map<String,Object> assembleMap(ResultSet resultSet,String flag,ConstantUtil constantUtil,TableUtil tableUtil) throws Exception{
    	Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("table_name_small",tableUtil.getTablename());
        dataMap.put("table_name",FormatUtil.replaceUnderLineAndUpperCase(tableUtil.getTablename()));
        dataMap.put("author",constantUtil.getAUTHOR());
        dataMap.put("date",constantUtil.getCURRENT_DATE());
        dataMap.put("package_name",constantUtil.getPackageName());
        dataMap.put("table_annotation",tableUtil.getTableAnnotation());
    	if("1".equals(flag)){
    		 return dataMap;
    	}
    	List<ColumnClass> columnClassList = new ArrayList<>();
        ColumnClass columnClass = null;
        while(resultSet.next()){
            if(resultSet.getString("COLUMN_NAME").equals("id")) continue;
            columnClass = new ColumnClass();
            columnClass.setColumnName(resultSet.getString("COLUMN_NAME"));
            columnClass.setColumnType(resultSet.getString("TYPE_NAME"));
            columnClass.setChangeColumnName(FormatUtil.replaceUnderLineAndUpperCase(resultSet.getString("COLUMN_NAME")));
            columnClass.setColumnComment(resultSet.getString("REMARKS"));
            columnClassList.add(columnClass);
        }
        dataMap.put("model_column",columnClassList);
        return dataMap;
    }

    public  Template getTemplate(String templateName,Configuration CONFIGURATION) throws IOException {
        try {
            return CONFIGURATION.getTemplate(templateName);
        } catch (IOException e) {
            throw e;
        }
    }

   /* public  void clearCache() {
        CONFIGURATION.clearTemplateCache();
    }*/

    //连接数据库
    public Connection getConnection(ConstantUtil constantUtil) throws Exception{
        Class.forName(constantUtil.getMYSQLDBDRIVER());
        Connection connection= DriverManager.getConnection(constantUtil.getMYSQLDBURL(), constantUtil.getMYSQLDBUSER(), constantUtil.getMYSQLDBPASSWORD());
        return connection;
    }

}
